/**
 * Created by calena on 2018/11/2.
 */

var chartPlay = {
    /*图表初始化元素*/
    chartDom: null,
    init: function () {
        var wrapper = $('.chart-show-wrapper');
        wrapper.show();
        this.chartDom = echarts.init(document.querySelector('#chartDom'));
        wrapper.hide();
    },
    renderChart: function (obj) {
        var _this = this;
        var chartPanel = $('#chartPlay');

        /*获取gis图形产品弹出层默认值*/
        _this.chartDefault();



        /*gis图形制作弹出层*/
        layLayer.open({
            title: '统计图表展示',
            type: 1,
            area: ['650px', '550px'],
            btn: '确认',
            content: chartPanel,
            yes: function (ind) {
                if ( !chartPanel.find('select[name="yAxis"]').val().length ) {
                    layLayer.msg('y轴字段请至少选择一个', {type:0, icon: 5, time: 1500});
                    return;
                }
                if ( chartPanel.find('select[name="xAxis"]').val() === chartPanel.find('select[name="dataCompare"]').val() ) {
                    layLayer.msg('对比字段与X轴不能相同', {type:0, icon: 5, time: 1500});
                    return;
                }
                // var loadMask = layLayer.load(0, {shade: [0.3, '#000']});
                /*获取面板数值*/
                var gisGraphicParam = {
                    xAxis: chartPanel.find('[name="xAxis"]').val(),   //x轴
                    yAxis: chartPanel.find('[name="yAxis"]').val(),    //y轴
                    mainTitle: chartPanel.find('[name="mainTitle"]').val(),      //主标题
                    subtitle: chartPanel.find('[name="subtitle"]').val(),     //副标题
                    compareField: chartPanel.find('[name="dataCompare"]').val()    //对比字段
                };

                /*数据排序*/
                tablePage.resultData=obj;//tablePage选择的站点数据
                tablePage.resultData = tablePage.resultData.sort(function (a, b) {
                    return Number(String(a[gisGraphicParam.xAxis]).replace(/-/g,'')) - Number(String(b[gisGraphicParam.xAxis]).replace(/-/g,''));
                });

                var xFiled = [],    //x轴字段
                    series = [],    //数据序列
                    legend = [];    //图例

                /*数据对比的操作*/
                if ( gisGraphicParam.compareField !== '' ) {
                    /*抽取对比字段序列*/
                    var compareField = [];
                    /*抽取x轴不重复字段*/
                    xFiled = tablePage.resultData.reduce(function (all, val) {
                        if ( all.indexOf(val[gisGraphicParam.xAxis]) === -1 ) {all.push(val[gisGraphicParam.xAxis]);}
                        if ( compareField.indexOf(val[gisGraphicParam.compareField]) === -1 ) {compareField.push(val[gisGraphicParam.compareField]);}
                        return all;
                    }, []);

                    /*遍历y轴字段*/
                    gisGraphicParam.yAxis.forEach(function (y) {
                        /*遍历对比字段，生成序列数据*/
                        compareField.forEach(function (val) {
                            var data = xFiled.map(function (item) {
                                var s = tablePage.resultData.filter(function (i) { return i[gisGraphicParam.compareField] === val && i[gisGraphicParam.xAxis] === item });
                                return s.length ? ( String(s[0][y]).indexOf('999') > -1 ? null : Number(s[0][y]) ) : null
                            });
                            var legendName = val + '-' +tablePage.tableHeadField[tablePage.tableEnglishField.indexOf(y)];
                            legend.push(legendName);
                            series.push({
                                type: 'line',
                                name: legendName,
                                data: data,
                                // smooth: true, //平滑
                                /*颜色*/
                                itemStyle: {
                                    color: randomColor()
                                }
                            });
                        });
                    });
                }
                /*普通操作*/
                else {
                    var color = $('#chartPlay').find('.y-axis-color').map(function () {return $(this).val()});

                    xFiled = tablePage.resultData.map(function (val) { return val[gisGraphicParam.xAxis] });

                    series = gisGraphicParam.yAxis.map(function (y, ind) {
                        var data = tablePage.resultData.map(function (val) { return ( String(val[y]).indexOf('999') > -1 ? null : Number(val[y]) ) });

                        var legendName = tablePage.tableHeadField[tablePage.tableEnglishField.indexOf(y)];
                        legend.push(legendName);
                        return {
                            type: 'bar',
                            name: legendName,
                            data: data,
                            // smooth: true, //平滑
                            /*颜色*/
                            itemStyle: {
                                color: color[ind]
                            }
                        }
                    });

                }

                /*跳转到统计图页面*/
                $('.content-nav .chart-nav').trigger('click');

                var option = {
                    /*标题*/
                    title: {
                        show: true,
                        text: gisGraphicParam.mainTitle,
                        subtext: gisGraphicParam.subtitle
                    },
                    /*图例*/
                    legend: {
                        orient: 'horizontal',
                        x : '3%',
                        y : '8%',
                        data: legend
                    },
                    /*提示框触发类型   样式*/
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        }
                    },
                    /*缩放  内置*/
                    dataZoom: [
                        {
                            type: 'inside'
                        }
                    ],
                    grid: {
                        left: '3%',
                        right: '10%',
                        bottom: '3%',
                        top: '18%',
                        containLabel: true

                    },
                    /*工具栏 样式*/
                    toolbox: {
                        show: true,
                        orient: 'vertical',
                        top: '40px',
                        right: '10px',
                        feature: {
                            dataView: {readOnly: false},
                            magicType: {type: ['line', 'bar']},
                            restore: {},
                            saveAsImage: {}
                        }
                    },
                    // 声明一个 X 轴，类目轴（category）。默认情况下，类目轴对应到 dataset 第一列。
                    xAxis: {
                        type: 'category',
                        name: gisGraphicParam.xAxis,
                        data: xFiled
                    },
                    // 声明一个 Y 轴，数值轴。
                    yAxis: {},
                    // 声明多个 bar 系列，默认情况下，每个系列会自动对应到 dataset 的每一列。
                    series: series
                };

                // 使用刚指定的配置项和数据显示图表。 第二个参数，是否不合并
                _this.chartDom.setOption(option, true);

                layLayer.close(ind)
            }
        });
    },
    /*获取图表默认值*/
    chartDefault: function () {
        var _this = this;
        var chartPanel = $('#chartPlay');

        /*xy轴*/
        var xAxis = ['时间','站号', '名称', '市'].map(function (val) {
            return '<option value="'+ val +'">'+ val +'</option>';
        }).join('');
        var compareAxis = ['站号', '名称', '市','时间' ].map(function (val) {
            return '<option value="'+ val +'">'+ val +'</option>';
        }).join('');

        var yAxis = tablePage.tableHeadField.reduce(function (all, cur, ind) {
            if ( ['站号', '名称', '市'].indexOf(cur) > -1 || cur.indexOf('时间') > -1 ) return all;
            return all += '<option value="'+ tablePage.tableEnglishField[ind] +'">'+ cur +'</option>';
        }, '<option value="">请选择统计类型</option>');
        chartPanel.find('select[name="xAxis"]').html(xAxis);
        chartPanel.find('select[name="dataCompare"]').html(compareAxis);
        chartPanel.find('select[name="yAxis"]').html(yAxis);

        /*主标题*/
        var mainTitle = function(){
            return Global.currentProvince +
                tablePage.tableHeadField[
                    tablePage.tableEnglishField.indexOf(
                        chartPanel.find('select[name="yAxis"]').val()[
                        chartPanel.find('select[name="yAxis"]').val().length - 1] ) ] +
                '统计图';
        };
        chartPanel.find('input[name="mainTitle"]').val(mainTitle());

        /*副标题*/
        chartPanel.find('input[name="subtitle"]').val(Global.gisTimeTitle);

        layForm.render(null, 'chartPlay');

        /*取一个值来改变标题，同时颜色主题修改，且判断至少选择一个*/
        layForm.on('select(chartYAxis)', function (data) {
            if ( !data.value.length ) {
                layLayer.msg('y轴字段请至少选择一个', {type:0, icon: 5, time: 1500});
                return;
            }
            chartPanel.find('input[name="mainTitle"]').val(mainTitle());
            // var themColor = data.value.map(function (val) {
            //   var color = randomColor();
            //   return '<label>'+ tablePage.tableHeadField[tablePage.tableEnglishField.indexOf(val)] +
            //     '：</label><input style="margin-right: 10px;" class="y-axis-color" type="color" value="'+ color +'" />'
            // });
            function themColor(){
                return data.value.map(function (val) {
                    var color = randomColor();
                    return '<label>'+ tablePage.tableHeadField[tablePage.tableEnglishField.indexOf(val)] +
                        '：</label><input style="margin-right: 10px;" class="y-axis-color" type="color" value="'+ color +'" />'
                }).join('');
            }
            chartPanel.find('.them-color').html(themColor());
            chartPanel.find('.them-color-compare').html(themColor());
        });
        /*y轴默认选择一个*/
        chartPanel.find('select[name="yAxis"]').next().find('div.layui-form-checkbox').eq(0).trigger('click');

    },
    dataChart: null,
    newChart: function( param ) {
        let _this = this,
            thisView = ``, optionView = ``,
            curStaticConfig = param.elmtParam;
            
        for ( let x = 0; x < curStaticConfig.length; x++ ) {
            optionView += `<option value="${ curStaticConfig[x].eleCode }">${ curStaticConfig[x].eleName }</option>`;
        }

        if ( !_this.dataChart ) {
            thisView = `<div class="dataChart">
                            <div class="layui-input-inline">
                                <select name="changeElmt">
                                    ${ optionView }
                                </select>
                            </div>
                            <div id="_chart"></div>
                        </div>`;

            param.insetElmt.insertAdjacentHTML("beforeEnd", thisView);
            elmtView = null;
            thisView = null;

            let _chart = param.insetElmt.querySelector("#_chart");

            _this.dataChart = echarts.init( _chart );
        } else {
            let selectView = param.insetElmt.querySelector("select[name='changeElmt']");
            selectView.textContent = "";
            selectView.insertAdjacentHTML("beforeEnd", optionView);
        }

        _this.drawChart( param );
    },
    drawChart: function( param ) {
        let _this = this,
            option = null;

        option = {
            title: {
                show: true,
                text: param.mainTitle || "",
                subtext: param.subTitle || "",
                left: 'center'
            },
            tooltip : {
                trigger: 'axis',
                axisPointer : { type : 'shadow' }
            },
            grid: {
                top: 70,
                left: 60,
                right: 20,
                bottom: 50,
                containLabel: false
            },
            xAxis : [{
                type : 'category',
                data : param.xAxis || [],
                axisTick: { alignWithLabel: true }
            }],
            yAxis: [{
                name: param.yAxis || "单位",
                type: 'value',
                axisPointer: { snap: true }
            }],
            legend: {
                data: param.legends || [],
                x: 'center', y: 'bottom'
            },
            series: param.series || []
        };

        _this.dataChart.clear();
        _this.dataChart.setOption( option );
        option = null;
    }
};
